package cn.edu.tju.elm.service;

import cn.edu.tju.core.model.Authority;
import cn.edu.tju.core.model.Person;
import cn.edu.tju.core.security.repository.AuthorityRepository;
import cn.edu.tju.core.security.repository.PersonRepository;
import cn.edu.tju.core.security.repository.UserRepository;
import cn.edu.tju.elm.dto.UserRegistrationDTO;
import cn.edu.tju.elm.dto.UserRegistrationResponseDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Set;

/**
 * ClassName: UserRegistrationService
 * Package: cn.edu.tju.elm.service
 * Description: 用户注册服务
 *
 * @Author Niu Wenhang
 * @Create 2025/9/21 22:00
 * @Version 1.0
 */
@Service
@Transactional
public class UserRegistrationService {

    @Autowired
    private PersonRepository personRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private AuthorityRepository authorityRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    public UserRegistrationResponseDTO registerUser(UserRegistrationDTO registrationDTO) {
        // 检查用户名是否已存在
        if (userRepository.existsByUsername(registrationDTO.getUsername())) {
            throw new IllegalArgumentException("用户名已存在");
        }

        // 检查邮箱是否已存在（仅当邮箱不为空时）
        if (registrationDTO.getEmail() != null && !registrationDTO.getEmail().trim().isEmpty()) {
            if (personRepository.existsByEmail(registrationDTO.getEmail())) {
                throw new IllegalArgumentException("邮箱已被使用");
            }
        }

        // 检查手机号是否已存在（仅当手机号不为空时）
        if (registrationDTO.getPhone() != null && !registrationDTO.getPhone().trim().isEmpty()) {
            if (personRepository.existsByPhone(registrationDTO.getPhone())) {
                throw new IllegalArgumentException("手机号已被使用");
            }
        }

        // 创建新用户（Person）
        Person person = new Person();
        person.setUsername(registrationDTO.getUsername());
        person.setPassword(passwordEncoder.encode(registrationDTO.getPassword()));
        
        // 只有非空字段才设置
        if (registrationDTO.getEmail() != null && !registrationDTO.getEmail().trim().isEmpty()) {
            person.setEmail(registrationDTO.getEmail());
        }
        if (registrationDTO.getPhone() != null && !registrationDTO.getPhone().trim().isEmpty()) {
            person.setPhone(registrationDTO.getPhone());
        }
        if (registrationDTO.getFirstName() != null && !registrationDTO.getFirstName().trim().isEmpty()) {
            person.setFirstName(registrationDTO.getFirstName());
        }
        if (registrationDTO.getLastName() != null && !registrationDTO.getLastName().trim().isEmpty()) {
            person.setLastName(registrationDTO.getLastName());
        }
        if (registrationDTO.getGender() != null && !registrationDTO.getGender().trim().isEmpty()) {
            person.setGender(registrationDTO.getGender());
        }
        person.setActivated(true);
        person.setCreator(0L); // 系统创建
        person.setCreateTime(LocalDateTime.now());
        person.setUpdater(0L); // 系统更新
        person.setUpdateTime(LocalDateTime.now());
        person.setDeleted(false);

        // 设置用户权限为USER
        Set<Authority> authorities = new HashSet<>();
        Authority userAuthority = authorityRepository.findByName("USER")
                .orElseThrow(() -> new IllegalArgumentException("USER权限不存在"));
        authorities.add(userAuthority);
        person.setAuthorities(authorities);

        // 保存用户
        Person savedPerson = personRepository.save(person);

        // 返回响应
        return new UserRegistrationResponseDTO(
                savedPerson.getId(),
                savedPerson.getUsername(),
                savedPerson.getEmail(),
                savedPerson.getPhone(),
                savedPerson.getFirstName(),
                savedPerson.getLastName(),
                "注册成功"
        );
    }

    public boolean isUsernameAvailable(String username) {
        return !userRepository.existsByUsername(username);
    }

    public boolean isEmailAvailable(String email) {
        // 如果邮箱为空，则认为可用
        if (email == null || email.trim().isEmpty()) {
            return true;
        }
        return !personRepository.existsByEmail(email);
    }

    public boolean isPhoneAvailable(String phone) {
        // 如果手机号为空，则认为可用
        if (phone == null || phone.trim().isEmpty()) {
            return true;
        }
        return !personRepository.existsByPhone(phone);
    }
}